<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Cat extends Model
{
	protected $table = 'cat';
	protected $primaryKey = 'id';
	public $timestamps = false;
	
	
	/**
	 * 添加节点
	 * $p[pid]
	 * $p['cat_name']
	 * $p['nav']
	 * $p[pos]
	 * @author wudi
	 */
	public static function add($p=[]){
		if(empty($p['cat_name'])){
			return false;
		}
		$p['add_date']=$p['add_date']??date('Y-m-d H:i:s');
		return DB::table('cat')->insert($p);
	}


	/**
	 * 删除节点 只能删除没有子类的节点
	 * $p['id']
	 */
	public static function del($p){
		$exists = DB::table('cat')->where('pid',$p['id'])->exists();
		if($exists){
			return false;
		}
		return DB::table('cat')->where('id',$p['id'])->delete();
	}


	public static function edit($p){
		if(empty($p['id'])){
			return false;
		}
		$id = $p['id'];
		unset($p['id']);
		return DB::table('cat')->where('id',$id)->update($p);
	}

	/**
	 * 获取一级子类
	 * @return [type] [description]
	 */
	public static function get_child($p){
		return DB::table('cat')->where('pid',$id)->orderBy('pos','desc')->get();
	}

	/**
	 * $p['id']
	 * @param  [type] $p [description]
	 * @return [type]    [description]
	 */
	public static function get_all_child($id=0,$rs=[],$level=0){
		$obj = DB::table('cat');
		if(1|| $id>0){
			$obj->where('pid',$id);
		}
		$all = $obj->orderBy('pos','desc')->get()->toArray();
		$all = arrays_set_key($all,'id');
		foreach($all as &$r){
			$r->level = $level;
		}

		$level++;
		foreach($all as $line){
			$rs = SELF::get_all_child($line->id,array_merge($rs,$all),$level);
			$all = array_merge($all,$rs);
		}

		return $all;
	}

	public static function get_ids($p){
		$ids = [];
		foreach($p as $v){
			$ids[] = $v->id;
		}
		return $ids;
	}
}